﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Gollie.Database;
using Gollie.Mail;

namespace Gollie.Controls
{
	public partial class CancelAccount : AuthenticationRequiredCustomerBaseUserControl
	{
		protected void Page_Load(object sender, EventArgs e)
		{
		}

		protected override void OnFirstHit(object sender, EventArgs e)
		{
			decimal saldo = Queries.GetTotalUserSaldo(this.UserInfo.Id);

			this.lblSaldo.Text = ObjectFormatter.GetCurrencyString(saldo);

			if (saldo > 0)
				this.lblWarning.Visible = true;
		}

		protected override void OnPostBack(object sender, EventArgs e)
		{
			try
			{
				string wwHash = Hash.GetHash(this.tbWachtwoord.Text);

				if (Queries.UserExists(this.UserInfo.Id, wwHash))
				{
					Queries.DeregisterUser(this.UserInfo.Id);
				}
				else
					throw new Exception("Incorrect wachtwoord");

				this.pnlDeregister.Visible = false;
				this.pnlSuccess.Visible = true;
				this.ErrorMessageControl1.Hide();

				MailClient.Queue(new EMail
				{
					Name = "cancelaccount",
					Recipients = this.UserInfo.Email,
					Args = new Dictionary<string, string>()
					{
							{ "{aanhef}", this.UserInfo.MailAanhef },
										    
					}
				});

				logger.Info("User '{0}' deregistered", this.UserInfo.Gebruikersnaam);

				Session.Abandon();
			}
			catch (Exception ex)
			{
				this.ErrorMessageControl1.Show();
				this.ErrorMessageControl1.Text = "Fout: " + ex.Message;
			}
		}
	}
}